package com.pospi.xstore.ui.caigou;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.maning.library.MClearEditText;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.mylhyl.circledialog.view.listener.OnCreateBodyViewListener;
import com.pospi.xstore.R;
import com.pospi.xstore.adapter.BillDetailAdapter;
import com.pospi.xstore.dao.GoodsDao;
import com.pospi.xstore.dto.CustomerBeen;
import com.pospi.xstore.dto.GoodsBeen;
import com.pospi.xstore.dto.GoodsDto;
import com.pospi.xstore.dto.StoreBeen;
import com.pospi.xstore.dto.SupBeen;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.http.MaxNO;
import com.pospi.xstore.ui.CaptureActivity;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.cash_ui.PointActivity;
import com.pospi.xstore.ui.cash_ui.PointGoodsActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.DoubleSave;
import com.pospi.xstore.util.ExpandLayout;
import com.pospi.xstore.util.GetData;
import com.pospi.xstore.util.SaveOrderInfo;
import com.pospi.xstore.view.swipemenulistview.SwipeMenu;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuCreator;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuItem;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuListView;
import com.yinglan.keyboard.HideUtil;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CgDetailActivity extends BaseActivity implements AdapterView.OnItemClickListener {
    @Bind(R.id.time_select)
    TextView time_select;
    @Bind(R.id.billno_xz)
    TextView billno_xz;
    @Bind(R.id.cgmd_xz)
    TextView cgmd_xz;
    @Bind(R.id.gys_xz)
    TextView gys_xz;
    @Bind(R.id.cgy_xz)
    TextView cgy_xz;
    @Bind(R.id.beizhu_xz)
    TextView beizhu_xz;
    @Bind(R.id.lv_goods_cgsh)
    SwipeMenuListView lv_goods_counts;
    @Bind(R.id.et_code_counts)
    EditText et_code_counts;
    @Bind(R.id.tv_money_xz)
    TextView tv_money_xz;
    @Bind(R.id.sh_xz)
    TextView sh_xz;
    @Bind(R.id.ll_title)
    LinearLayout ll_title;
    @Bind(R.id.tv_shop_title)
    TextView tv_shop_title;
    @Bind(R.id.expandLayout)
    ExpandLayout expandLayout;
    @Bind(R.id.sh_bg)
    ImageView sh_bg;
    @Bind(R.id.save_xz)
    TextView save_xz;
    @Bind(R.id.tv_expand)
    TextView tv_expand;

    private GoodsDao dao;
    private List<GoodsBeen> goodsDtos = new ArrayList<>();

    private BillDetailAdapter adapter;
    private CgddBeen cgddBeen;
    List<String> strings = new ArrayList<>();
    private List<StoreBeen> storeBeens;
    private List<CustomerBeen> customerBeens;
    private CustomerBeen customerBeen = new CustomerBeen();
    private SupBeen supBeen = new SupBeen();
    private MClearEditText sl;
    private MClearEditText dj;
    private boolean isEdite = true;
    private String billId = "0";//新单据为0
    private String billNo = "";
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case RE_SUCESS:
                    getNetData((String) msg.obj);
                    break;
                case 2:

                    break;
                case 3:

                    break;
                case 4:

                    break;
            }

        }
    };

    private void getNetData(String obj) {
        try {
            JSONObject object = new JSONObject(obj);
            JSONObject result = object.getJSONObject("result");
            JSONObject head = result.getJSONObject("head");
            billNo = head.getString("billno");
            billId = head.getString("id");
            cgddBeen.setId(head.getString("id"));
            billno_xz.setText(billNo);
            new CircleDialog.Builder()
                    .setTitle("提示")
                    .setText("保存成功")
                    .setPositive("确定", null)
                    .show(getSupportFragmentManager());
            sh_xz.setText("审核");

            Log.i("data", object.getString("errMsg"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.cgsh_detail2);
        ButterKnife.bind(this);
        setTitle("采购单新增");
        tv_shop_title.setText("采购门店");

        expandLayout.initExpand(true);

        dao = new GoodsDao(getApplicationContext());
        time_select.setText(GetData.getYYMMDDTime());
        adapter = new BillDetailAdapter(this, goodsDtos);
        lv_goods_counts.setAdapter(adapter);
        cgddBeen = (CgddBeen) getIntent().getSerializableExtra("data");
        if (cgddBeen != null) {//修改表单
            billId = cgddBeen.getId();
            billNo = cgddBeen.getBillno();
            sh_xz.setText("审核");
            setTitle("采购单修改");
            supBeen.setId(cgddBeen.getSupid());
            time_select.setText(cgddBeen.getBillrq());
            billno_xz.setText(cgddBeen.getBillno());
            cgmd_xz.setText(cgddBeen.getMarketname());
            gys_xz.setText(cgddBeen.getSupname());
            getData();
            if (!cgddBeen.getStatus().equals("1")) {
                setTitle("详情");
                sh_xz.setVisibility(View.GONE);
                save_xz.setVisibility(View.GONE);
                sh_bg.setVisibility(View.VISIBLE);
                isEdite = false;
                ll_title.setVisibility(View.INVISIBLE);
            }
        } else {
            cgddBeen = new CgddBeen();

        }


        lv_goods_counts.setOnItemClickListener(this);


        setSwipeListView();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String goodsInfo = intent.getStringExtra("data");
        SupBeen been = (SupBeen) intent.getSerializableExtra("sup");

        if (been != null) {
            gys_xz.setText(been.getName());
            supBeen = been;
        }
        if (goodsInfo != null) {
            List<GoodsBeen> list = new ArrayList<>();
            list = SaveOrderInfo.changegoodsToList(goodsInfo);
            goodsDtos.addAll(list);
            adapter.notifyDataSetChanged();
            setJe();
        }

        Log.i("goods", goodsInfo + "------");

    }

    @Override
    protected void onStart() {
        super.onStart();
        et_code_counts.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                Log.i("num", "ooo");
                search(et_code_counts.getText().toString().trim());
                return false;
            }
        });
    }

    private void check(GoodsBeen gd) {
        for (GoodsBeen dto : goodsDtos) {
            if (dto.getId().equals(gd.getId())) {
                dto.setSl(DoubleSave.doubleSaveTwo(dto.getSl() + 1));
                return;
            }
        }
        goodsDtos.add(gd);

    }

    private void search(String code) {
        if (gys_xz.getText().toString().isEmpty()) {
            Toast.makeText(this, "供应商不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (cgmd_xz.getText().toString().isEmpty()) {
            Toast.makeText(this, "门店不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        search();
        //搜索
//        GoodsBeen goodsDto = dao.selectGoods(code);
//        if (goodsDto != null) {
//            check(goodsDto);
//        } else {
//            Toast.makeText(this, "商品不存在", Toast.LENGTH_SHORT).show();
////
//        }
//        et_code_counts.setText("");
//        adapter.notifyDataSetChanged();
//        lv_goods_counts.setFocusable(false);
//        ETRequestFocus();
//        setJe();
    }

    //下载商品
    private void search() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "bill.mbillcgdd");
        params.put("type", Constant.BILL_TYPE_CGDD);
        params.put("fun", "find_goods");

        params.put("page", "");
        params.put("limit", "");

        params.put("market", cgddBeen.getMarket());
        params.put("supid", supBeen.getId());

        JSONObject object = new JSONObject();
        try {
            object.put("filter", et_code_counts.getText().toString().trim());

        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.put("pds", object);

        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, final byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    final JSONObject object1 = new JSONObject(new String(bytes));
                    Log.i("login", object1.getString("errMsg"));
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                searchGoods(object1.getJSONArray("result"));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }

    private void searchGoods(JSONArray result) {
        List<GoodsBeen> sGoodsBeens = SaveOrderInfo.changegoodsToList(result.toString());
        goodsDtos.addAll(sGoodsBeens);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                et_code_counts.setText("");
                adapter.notifyDataSetChanged();
                lv_goods_counts.setFocusable(false);
                ETRequestFocus();
                setJe();
            }
        });
    }


    public void ETRequestFocus() {
        et_code_counts.setFocusable(true);
        et_code_counts.setFocusableInTouchMode(true);
        et_code_counts.requestFocus();
    }

    private void creatDialog(List<String> ss) {

        new CircleDialog.Builder(this)
                .setItems(ss, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        //门店
                        cgmd_xz.setText(storeBeens.get(i).getName());

                        cgddBeen.setMarket(storeBeens.get(i).getId());
                    }
                })
                .setGravity(Gravity.CENTER)
                .show();
    }

    private void creatDialog2(List<String> ss) {

        new CircleDialog.Builder(this)
                .setItems(ss, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        //采购员
                        cgy_xz.setText(customerBeens.get(i).getName());
                        customerBeen = customerBeens.get(i);
                    }
                })
                .setGravity(Gravity.CENTER)
                .show();
    }

    private void requestCemera() {
        if (PermissionsUtil.hasPermission(this, Manifest.permission.CAMERA)) {
            //有访问摄像头的权限
            //扫描
            Intent intent = new Intent(CgDetailActivity.this, CaptureActivity.class);
            startActivityForResult(intent, 1);
        } else {
            PermissionsUtil.requestPermission(this, new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    //用户授予了访问摄像头的权限
                    //扫描
                    Intent intent = new Intent(CgDetailActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, 1);
                }


                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                    //用户拒绝了访问摄像头的申请
                }
            }, new String[]{Manifest.permission.CAMERA});
        }
    }

    @OnClick({R.id.time_select, R.id.cgmd_xz, R.id.gys_xz, R.id.cgy_xz, R.id.iv_search_counts, R.id.save_xz, R.id.sh_xz, R.id.tv_expand})
    public void onClick(View view) {
        if (!isEdite) {
            Toast.makeText(this, "已审核，不可编辑", Toast.LENGTH_SHORT).show();
            return;
        }
        switch (view.getId()) {
            case R.id.tv_expand:
                expandLayout.toggleExpand();
                if (expandLayout.isExpand()) {
                    tv_expand.setBackground(getResources().getDrawable(R.drawable.drop_down_selected_icon));

                } else {
                    tv_expand.setBackground(getResources().getDrawable(R.drawable.drop_down_unselected_icon));
                }
                break;
            case R.id.sh_xz:
                if (sh_xz.getText().toString().equals("审核")) {
                    showConfirm();
                } else {
                    finish();
                }
                break;
            case R.id.save_xz:
                saveBill();

                break;
            case R.id.iv_search_counts:

                if (gys_xz.getText().toString().isEmpty()) {
                    Toast.makeText(this, "供应商不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (cgmd_xz.getText().toString().isEmpty()) {
                    Toast.makeText(this, "门店不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent = new Intent(this, PointActivity.class);
                intent.putExtra("mark", "CgDetailActivity");
                intent.putExtra("market", cgddBeen.getMarket());
                intent.putExtra("supid", supBeen.getId());
                startActivity(intent);
                break;
//            case R.id.iv_scan_xz:
//                requestCemera();
//                break;
            case R.id.cgmd_xz:
                storeBeens = SaveOrderInfo.changeStoreToList(SPHelper.getInstance().getString(Constant.STORE_LIST));
                strings.clear();
                for (StoreBeen been : storeBeens) {
                    strings.add(been.getName());
                }
                creatDialog(strings);

                break;
            case R.id.gys_xz:
                Intent supIntent = new Intent(this, SupActivity.class);
                supIntent.putExtra("mark", "CgDetailActivity");
                startActivity(supIntent);
                break;
            case R.id.cgy_xz:
                customerBeens = SaveOrderInfo.changeCusToList(SPHelper.getInstance().getString(Constant.CUS_LIST));
                strings.clear();
                for (CustomerBeen been : customerBeens) {
                    strings.add(been.getName());
                }
                creatDialog2(strings);
                break;
            case R.id.time_select:
                TimePickerDialog dialogYearMonthDay2 = new TimePickerDialog.Builder()
                        .setType(Type.YEAR_MONTH_DAY)
                        .setTitleStringId("选择日期")
                        .setWheelItemTextSize(16)
                        .setCallBack(new OnDateSetListener() {
                            @Override
                            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                                Date date = new Date(millseconds);
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                                String time = format.format(date);
                                time_select.setText(time);
                            }
                        })
                        .build();
                dialogYearMonthDay2.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
                break;

        }
    }

    //保存
    private void saveBill() {
        if (goodsDtos.size() == 0) {
            Toast.makeText(this, "请至少插入一条商品", Toast.LENGTH_SHORT).show();
            return;
        }
        if (gys_xz.getText().toString().isEmpty()) {
            Toast.makeText(this, "供应商不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (cgmd_xz.getText().toString().isEmpty()) {
            Toast.makeText(this, "门店不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        RequestParams params = new RequestParams();
        params.put("model", "bill.mbillcgdd");
        params.put("fun", "save");
        params.put("type", Constant.BILL_TYPE_CGDD);
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("pds", getJson());
        requestNet(params, handler);

    }

    private String getJson() {
        JSONObject object = new JSONObject();
        JSONObject bill = new JSONObject();
        JSONArray array = new JSONArray();
        try {
            object.put("id", billId);//新单据传入0
            object.put("billno", billNo);//
            object.put("status", "1");//"1"="未审核""2"="已审核" "3"="已复核" "4"="作废"
            object.put("supid", supBeen.getId());
            object.put("jyfs", "");

            object.put("billrq", time_select.getText().toString().trim());
            object.put("memo", "");
            object.put("person1", "");
            object.put("type", Constant.BILL_TYPE_CGDD);
            object.put("market", cgddBeen.getMarket());

            for (GoodsBeen been : goodsDtos) {
                JSONObject detail = new JSONObject();
                detail.put("id", "");
                detail.put("num", been.getNum());
                detail.put("name", been.getName());
                detail.put("goodsid", been.getId());
                detail.put("barcode", been.getBarcode());
                detail.put("spec", been.getSpec());

                detail.put("unit", been.getUnit());
                detail.put("hl", been.getHl());
                detail.put("sl", been.getSl());
                detail.put("dj", been.getDj());
                if (been.getZkl() == null) {
                    been.setZkl("1");

                }
                detail.put("zkl", been.getZkl());

                detail.put("je", been.getDj() * been.getSl() * Double.parseDouble(been.getZkl()));

                detail.put("jj", been.getJj());
                detail.put("jjje", been.getJj() * been.getSl());
                detail.put("lsj", been.getLsj());
                detail.put("lsjje", been.getLsj() * been.getSl());
                detail.put("catid", been.getCatid());
                detail.put("brandid", been.getBrandid());

                detail.put("artno", been.getArtno());
                detail.put("memo", been.getMemo());
                detail.put("baseunit", been.getBaseunit());
                detail.put("jhl", been.getJhl());
                detail.put("junit", been.getJunit());
                array.put(detail);
            }


            bill.put("head", object);
            bill.put("detail", array);


        } catch (JSONException e) {
            e.printStackTrace();
        }

        return bill.toString();
    }

    //审核
    private void shBill() {
        RequestParams params = new RequestParams();
        params.put("model", "bill.mbillcgdd");
        params.put("fun", "audit");
        params.put("type", Constant.BILL_TYPE_CGDD);
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));

        JSONObject object = new JSONObject();
        try {
            object.put("id", billId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        params.put("pds", object.toString());
        requestAudit(params, CgshListActivity.class, this);
    }

    private void setSwipeListView() {
        // step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem openItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                openItem.setBackground(new ColorDrawable(Color.rgb(0xD9, 0x47,
                        0x47)));
                // set item width
                openItem.setWidth(dp2px(90));
                // set item title
                openItem.setTitle("删除");
                // set item title fontsize
                openItem.setTitleSize(18);
                // set item title font color
                openItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(openItem);
            }
        };
        // set creator
        lv_goods_counts.setMenuCreator(creator);

        // step 2. listener item click event
        lv_goods_counts.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
//                GoodsDto item = goodsDtos.get(position);
//					delete(item);
                goodsDtos.remove(position);
                adapter.notifyDataSetChanged();
                setJe();
            }
        });

        // set SwipeListener
        lv_goods_counts.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    private void setJe() {
        double mo = 0;
        for (GoodsBeen dto : goodsDtos) {
            mo += dto.getSl() * dto.getDj();
        }
        tv_money_xz.setText(DoubleSave.doubleSaveTwo(mo) + "");
    }

    private void getData() {
        RequestParams params = new RequestParams();
        params.put("model", "bill.mbillcgdd");
        params.put("fun", "find_detail");
        params.put("type", Constant.BILL_TYPE_CGDD);
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        JSONObject object = new JSONObject();
        try {
            object.put("id", cgddBeen.getId());
        } catch (JSONException e) {
        }

        params.put("pds", object.toString());
        LoadServer.getConnect(this, Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("data", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONObject result = jsonObject.getJSONObject("result");
                    saveGoods(result);


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }

    private void saveGoods(JSONObject response) {
        List<GoodsBeen> list = new ArrayList<>();
        try {
            JSONArray array = response.getJSONArray("detail");

            list = SaveOrderInfo.changegoodsToList(array.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }


        goodsDtos.addAll(list);
        adapter.notifyDataSetChanged();
        setJe();

    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (!isEdite) {
            Toast.makeText(this, "已审核，不可编辑", Toast.LENGTH_SHORT).show();
            return;
        }
        final GoodsBeen goodsBeen = goodsDtos.get(i);
        new CircleDialog.Builder(this)
                .setBodyView(R.layout.dialog_layout, new OnCreateBodyViewListener() {
                    @Override
                    public void onCreateBodyView(View view) {
                        sl = view.findViewById(R.id.et_goods_num);
                        dj = view.findViewById(R.id.et_goods_dj);
                        String s = goodsBeen.getSl() + "";
                        String d = goodsBeen.getDj() + "";
                        sl.setText(s);
                        dj.setText(d);
                        sl.setSelection(s.length());
                        dj.setSelection(d.length());
                        sl.setOnClearClickListener(new MClearEditText.OnClearClickListener() {
                            @Override
                            public void onClick() {
                                isHide = true;
                            }
                        });
                        dj.setOnClearClickListener(new MClearEditText.OnClearClickListener() {
                            @Override
                            public void onClick() {
                                isHide = true;
                            }
                        });
                    }
                })
                .setPositive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        hintKbOne();
                        if (isNumber(sl.getText().toString().trim())) {
                            goodsBeen.setSl(Double.parseDouble(sl.getText().toString().trim()));
                        }
                        if (isNumber(dj.getText().toString().trim())) {
                            goodsBeen.setDj(Double.parseDouble(dj.getText().toString().trim()));
                        }
                        adapter.notifyDataSetChanged();
                        setJe();

                    }
                })
                .setCancelable(false)
                .setTitle(goodsBeen.getName())
                .setNegative("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        hintKbOne();
                    }
                })
                .show();

    }

    public static boolean isNumber(String str) {
        String reg = "^[0-9]+(.[0-9]+)?$";
        return str.matches(reg);
    }

    private void showConfirm() {
        if (goodsDtos.size() == 0) {
            Toast.makeText(this, "请至少插入一条商品", Toast.LENGTH_SHORT).show();
            return;
        }
        if (gys_xz.getText().toString().isEmpty()) {
            Toast.makeText(this, "供应商不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (cgmd_xz.getText().toString().isEmpty()) {
            Toast.makeText(this, "门店不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        new CircleDialog.Builder()
                .setTitle("提示")
                .setText("是否审核，审核后不可修改")
                .setPositive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        shBill();
                    }
                })
                .setNegative("取消", null)
                .show(getSupportFragmentManager());
    }

    private boolean isHide = false;

    private void hintKbOne() {
        if (isHide) {
            InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            // 得到InputMethodManager的实例
            if (imm.isActive()) {
                // 如果开启
                imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                        InputMethodManager.HIDE_NOT_ALWAYS);

            }
            isHide = false;
        }

    }


}
